
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

function createTree(arr) {
  let NodeArr = [];
  for(let i = 0; i < arr.length; i++) {
    if(arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for(let i = 0; i < arr.length; i++) {
    if(NodeArr[i] == null) continue;
    if(2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if(2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function showTree(root) {
  // 层次遍历
  let NodeArr = [], value = [];
  NodeArr.push(root);
  value.push(root.val);
  while(NodeArr.length) {
    let tempNode = NodeArr[0];
    NodeArr = NodeArr.slice(1, NodeArr.length);
    console.log(NodeArr);
    if(tempNode == null) continue;
    if(tempNode.left) {
      NodeArr.push(tempNode.left);
      value.push(tempNode.left.val);
    }
    if(tempNode.right) {
      NodeArr.push(tempNode.right);
      value.push(tempNode.right.val);
    }
  }
  for(let i = 0; i < value.length; i++)
    console.log(value[i]);
}

/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
  if(root == null)
    return [];
  // let root = createTree(root1);
  // showTree(root);
  let nodeArr = [], result = [], level = 0, valueLevel = [];
  nodeArr.push({
    node: root,
    level
  });
  while(nodeArr[0]) {
    // 把数组的第一个剔除
    const { node, level: oldLevel } = nodeArr[0];
    nodeArr = nodeArr.slice(1, nodeArr.length);
    valueLevel.push({
      value: node.val,
      level: oldLevel
    });
    if(node.left){
      nodeArr.push({
        node: node.left,
        level: oldLevel + 1
      });
    }
    if(node.right){
      nodeArr.push({
        node: node.right,
        level: oldLevel + 1
      });
    }
  }
  result[0] = [valueLevel[0].value];
  if(valueLevel.length == 1)
    return result;
  let tempArr = [];
  for(let i = 1; i < valueLevel.length; i++) {
    if(valueLevel[i].level !== valueLevel[i - 1].level && i != 1) {
      result[valueLevel[i - 1].level] = [...tempArr];
      tempArr = [];
    }
    tempArr.push(valueLevel[i].value);
  }
  result[valueLevel[valueLevel.length - 1].level] = [...tempArr];
  return result;
};
let root = [3,9,20,null,null,15,7];
console.log(levelOrder(root));
root = [1];
console.log(levelOrder(root));


